﻿using AutoMapper;
using B.S.BasicData.Api.Read.Application.Command.Permission;
using B.S.BasicData.Api.Read.DTOS;
using B.S.BasicData.Domain.Entity;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infastructure.Interface;
using MediatR;

namespace B.S.BasicData.Api.Read.Application.Handler.Permission
{
    public class GetUserMenuTreeHandler : IRequestHandler<GetUserMenuTreeCommand, List<UserMenuDto>>
    {
        private readonly IBaseRepository<RolePermissionModel> _rolepermission;
        private readonly IBaseRepository<PathModel> _menuRepository;
        private readonly IMapper _mapper;
        public GetUserMenuTreeHandler(IBaseRepository<RolePermissionModel> rolepermission, IBaseRepository<PathModel> menuRepository, IMapper mapper)
        {
            _rolepermission = rolepermission;
            _menuRepository = menuRepository;
            _mapper = mapper;
        }
        /// <summary>
        /// 根据角色获取用户菜单权限树
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<List<UserMenuDto>> Handle(GetUserMenuTreeCommand request, CancellationToken cancellationToken)
        {
            List<UserMenuDto> result = new List<UserMenuDto>();

            // 1. 根据中间表查询所有角色对应的菜单ID
            var menuIds = _rolepermission.GetAll().Where(p => request.RoleIds.Contains(p.RId)).Select(p => p.MId).Distinct().ToList();
            //2.再用菜单Id查询出对应的菜单
            var menuall=_menuRepository.GetAll().Where(p=>menuIds.Contains(p.Id) && p.IsDelete==false).ToList();

            // 先找出所有menuall中的所有父ID
            var allParentIds = menuall.Select(m => m.PartentId).Distinct().ToList();
            // 找出所有menuall中没有被包含为子节点的父ID--就是父级Id
            var rootIds = allParentIds.Except(menuall.Select(m => m.Id)).ToList();
            // 如果rootIds为空，默认用0
            if (!rootIds.Any()) rootIds.Add(0);

            List<UserMenuDto> menuTree = new List<UserMenuDto>();
            foreach (var rootId in rootIds)
            {
                menuTree.AddRange(SlectMenuTree(menuall, rootId));
            }

            return Task.FromResult(menuTree);
        }
        /// <summary>
        /// 用户递归菜单树
        /// </summary>
        /// <param name="menuall"></param>
        /// <param name="v"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        private List<UserMenuDto> SlectMenuTree(List<PathModel> menuall, long partentId)
        {
            return menuall.Where(p => p.PartentId == partentId).Select(m => new UserMenuDto
            {
                Id = m.Id,
                MenuName = m.MenuName,
                Url = m.Url,
                Children= SlectMenuTree(menuall,m.Id)
            }).ToList();

        }
    }
}
